package ruler.services;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import ruler.main.R;

import android.content.SharedPreferences;
import android.os.Looper;
import android.preference.PreferenceManager;

public class RulerServiceThread extends Thread {

	private ScheduledExecutorService scheduler;
	private RulerService rulerService;
	private Looper looper;
	private int pollingInterval = 1;

	public RulerServiceThread(RulerService rulerService) {
		super();
		this.rulerService = rulerService;
		scheduler = Executors.newScheduledThreadPool(1);
	}

	public void run() {
		Looper.prepare();
		readPreferences();
		scheduler.scheduleWithFixedDelay(new PollingTask(rulerService), 1,
				pollingInterval, TimeUnit.SECONDS);
		this.looper = Looper.myLooper();
		Looper.loop();
	}

	public void requestStop() {
		scheduler.shutdown();
		this.looper.quit();
	}

	private void readPreferences() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(rulerService.getBaseContext());
		pollingInterval = prefs
				.getInt(rulerService.getResources().getString(
						R.string.pollingInterval), 1);
	}

}
